package com.example.joker.abao00.HttpUtil;

import android.content.Context;
import android.util.Log;

import com.example.joker.abao00.model.CookbookBean;
import com.example.joker.abao00.model.Msg;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Joker on 2015/12/7.
 */
public  class Utility {
    public synchronized static Msg handleReplyFromServer(Context context,String response) {   //没必要static因为压根没静态字段
        Log.d("respnsetext",response);
        Msg msg=new Msg();
        msg.setType(Msg.TYPE_RECEIVED);
        Gson gson = new Gson();

        if (response != null) {
            try {
                JSONObject jsonObject = new JSONObject(response);

                int mCode = jsonObject.getInt("code");
                if (mCode == 100000) {
                    msg.setCode(mCode);
                    msg.setReplyText(jsonObject.getString("text"));
                }

                if (mCode == 200000) {

                    msg.setCode(mCode);
                    msg.setReplyText(jsonObject.getString("text"));
                    msg.setURL(jsonObject.getString("url"));
                }

                if (mCode == 308000) {     //Gson解析嵌套JSON格式,必须事先新建一个Bean类,见书签

                    CookbookBean cookbookBean = gson.fromJson(response, new TypeToken<CookbookBean>(){}.getType());
                    msg.setCode(mCode);
                    msg.setReplyText(cookbookBean.getText());
                    msg.setList(cookbookBean.getList());

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        return msg;

    }
}
